package com.sxhuayuan.parking.service.impl;

import com.sxhuayuan.parking.compenent.Filter;
import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.dao.BaseDao;
import com.sxhuayuan.parking.dao.MonthlyProfitDao;
import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.entity.MonthlyProfit;
import com.sxhuayuan.parking.service.MonthlyProfitService;
import com.sxhuayuan.parking.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * 代理分润月结算
 * 
 * @author 何龙
 * @create 2019-05-22 17:26
 */
@Repository("monthlyProfitServiceImpl")
public class MonthlyProfitServiceImpl extends BaseServiceImpl<MonthlyProfit, Long> implements MonthlyProfitService {

	@Autowired
	MonthlyProfitDao dao;

	@Override
	public BaseDao<MonthlyProfit, Long> getDAO() {
		return dao;
	}

	@Override
	public Page<MonthlyProfit> findByPageable(Pageable pageable, Agent agent) {
		StringBuilder sb = new StringBuilder("select m from MonthlyProfit m ");
		if (agent != null && agent.getId() != null) {
			sb.append("join AgentRelation r on m.agent=r.child and r.parent.id=").append(agent.getId()).append(" ");
		} else {
			sb.append("where 1=1 ");
		}
		List<Filter> filters = pageable.getFilters();
		if (filters != null) {
			for (Filter filter : filters) {
				sb = setCondition(sb, filter);
			}
		}
		sb.append(" order by m.createDate desc");
		return findPage(sb.toString(), sb.toString().replace("select m", "select count(m.id)"), pageable.getPageSize(), pageable.getPageNumber());
	}

	@Override
	public BigDecimal[] sumByPage(Pageable pageable, Agent agent) {
		BigDecimal[] bigDecimals = new BigDecimal[3];
		StringBuilder sb = new StringBuilder("select sum(m.totalProfit),sum(m.weixinProfit),sum(m.alipayProfit) from MonthlyProfit m ");
		if (agent != null && agent.getId() != null) {
			sb.append("join AgentRelation r on m.agent=r.child and r.parent.id=").append(agent.getId()).append(" ");
		} else {
			sb.append("where 1=1 ");
		}
		List<Filter> filters = pageable.getFilters();
		if (filters != null) {
			for (Filter filter : filters) {
				sb = setCondition(sb, filter);
			}
		}

		Query query = entityManager.createQuery(sb.toString());
		List resultList = query.getResultList();
		if (resultList.size() > 0) {
			Object[] o = (Object[]) resultList.get(0);
			bigDecimals[0] = o[0] == null ? BigDecimal.ZERO : (BigDecimal) o[0];
			bigDecimals[1] = o[1] == null ? BigDecimal.ZERO : (BigDecimal) o[1];
			bigDecimals[2] = o[2] == null ? BigDecimal.ZERO : (BigDecimal) o[2];
		} else {
			bigDecimals[0] = BigDecimal.ZERO;
			bigDecimals[1] = BigDecimal.ZERO;
			bigDecimals[2] = BigDecimal.ZERO;
		}
		return bigDecimals;
	}

	@Override
	public MonthlyProfit findByAgentAndStatistisMonth(Agent agent, LocalDate month) {
		LocalDate minDate = DateUtils.getMinDate(month);
		LocalDate maxDate = DateUtils.getMaxDate(month);
		List<MonthlyProfit> list = dao.findByAgentAndMonth(agent, minDate, maxDate);
		if (list.size()>0){
			return list.get(0);
		}else {
			return null;
		}
	}

	private StringBuilder setCondition(StringBuilder sb, Filter filter) {
		if (filter.getProperty() == null || filter.getProperty().equals("") || filter.getValue() == null || filter.getValue().equals("")) {
			return sb;
		}
		switch (filter.getProperty()) {

		case "istartTime": {
			return sb.append(" and m.statistisMonth>='").append(filter.getValue()).append("' ");
		}
		case "iendTime": {
			return sb.append(" and m.statistisMonth<='").append(filter.getValue()).append("' ");
		}
		case "agentName": {
			return sb.append(" and m.agent.name='").append(filter.getValue()).append("' ");
		}
		case "parentAgentName": {
			return sb.append(" and m.agent.parent.name='").append(filter.getValue()).append("' ");
		}
		case "level": {
			Integer level = (Integer) filter.getValue();
			if (level == -1) {
				return sb.append(" and  m.agent.parent is null ");
			} else if (level == -2) {
				return sb.append(" and r.level!=0 ");
			} else if (level >= 0) {
				return sb.append(" and r.level=").append(level).append(" ");
			} else {
				return sb;
			}
		}
		default:
			return sb;
		}
	}

	/**
	 * 为保证每个代理的月结算统计信息每月只有一条
	 * 
	 * @param entity
	 */
	@Override
	public void save(MonthlyProfit entity) {
		LocalDate m = entity.getStatistisMonth();
		LocalDate start = DateUtils.getMinDate(m);
		LocalDate end = DateUtils.getMaxDate(m);
		List<MonthlyProfit> list = dao.findByAgentAndMonth(entity.getAgent(), start, end);
		if (list.size() > 0) {
			for (MonthlyProfit monthlyProfit : list) {
				dao.delete(monthlyProfit);
			}
		}
		super.save(entity);
	}
}
